package com.zhang.gulimall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import com.zhang.gulimall.order.entity.OrderEntity;
import com.zhang.gulimall.order.enume.OrderStatusEnum;
import com.zhang.gulimall.order.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "order.release.order.queue")
@Service
public class MyRabbitListener {
    @Autowired
    OrderService orderService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @RabbitHandler
    private void closeOrder(String orderSn, Message message, Channel channel) throws IOException {
        System.out.println("收到过期消息,进行关单=============================================================");
        try {
            OrderEntity orderEntity = orderService.getOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderSn,orderSn));
            if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
                orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
                orderService.updateById(orderEntity);
                // 发送订单取消消息,相当于二次确认,如果不加可能会因为订单消息过慢导致取消的时候库存早已接受消息
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other", orderEntity.getOrderSn());
            }

            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
